package cn.itlaobing.dao;
import cn.itlaobing.util.IRowMapping;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static cn.itlaobing.util.Iconstants.*;
/**
 * Created by admin on 2017/11/10.
 */
public class DBHelper<T> {
   static String DRIVER="com.mysql.jdbc.Driver";
    String URL="jdbc:mysql://localhost:3306/train?characterEncoding=utf8";
    String USER="root";
    String PWD="root";
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    //打开连接
    private void  openConnection()throws SQLException {
        if (conn==null || conn.isClosed()){
            conn= DriverManager.getConnection(URL,USER,PWD);
        }
    }
    //关闭资源
    public void close()throws SQLException{
        if (rs!=null)rs.close();
        if (ps!=null)ps.close();
        if (conn!=null)conn.close();
    }
    //设置占位符
    public  void setPeras(Object ...obj)throws  SQLException,ClassNotFoundException{
        if (obj!=null || obj.length>0){
        for (int i=0;i<obj.length;i++){
            ps.setObject(i+1,obj[i]);
        }
        }
    }
    //增删改的辅助方法
    public  int addDelUpdate(String sql,Object...obj)throws SQLException,ClassNotFoundException{
        openConnection();
        ps=conn.prepareStatement(sql);
        setPeras(obj);
        return  ps.executeUpdate();
    }
    //查询的辅助方法
    public  ResultSet select(String sql,Object ...obj)throws  SQLException,ClassNotFoundException{
        openConnection();
        ps=conn.prepareStatement(sql);
        setPeras(obj);
        return ps.executeQuery();
    }
    //全查的辅助方法
    public List<T> selectAll(IRowMapping<T> rowMapping, String sql,Object ...obj)throws SQLException,ClassNotFoundException{
        List<T> list=new ArrayList<T>();
        rs=select(sql, obj);
        while (rs.next()){
            T t=rowMapping.mapping(rs);
            list.add(t);
        }
        return list;
    }
    //单查的辅助方法
    public Object selectSigln(String sql, Object ...obj)throws  SQLException,ClassNotFoundException{
        rs=select(sql,obj);
        while (rs.next()){
            return  rs.getObject(1);
        }
        return null;
    }
}
